package cc.rengu.igas.share.core.service.channel.upqc;

import cc.rengu.igas.channel.upqc.facade.base.Header;
import cc.rengu.igas.channel.upqc.facade.bean.AddnCondition;
import cc.rengu.igas.channel.upqc.facade.bean.PayerInfo;
import cc.rengu.igas.channel.upqc.facade.request.GenC2BNoRequest;
import cc.rengu.igas.channel.upqc.facade.response.GenC2BNoResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.enums.ChannelCallModeEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.PayTypeEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.GlobalTransUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.Objects;

/**
 * UPQC-C2B码申请
 * Created by lzl on 2021/4/23 11:08
 */
public class GenC2BNoService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header upqcHeader = new Header();
        upqcHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        upqcHeader.setChanlId(channelCallCfg.getMsgSrcId());
        upqcHeader.setSrcSysId(AppParamConstant.SYS_ID);
        upqcHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        upqcHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        upqcHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        upqcHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        upqcHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        upqcHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        GenC2BNoRequest genC2BNoRequest = new GenC2BNoRequest();
        ConvertUtil.convertOutput(genC2BNoRequest);
        genC2BNoRequest.setHeader(upqcHeader);
        // 付款方信息	payerInfo
        PayerInfo upPayerBean = new PayerInfo();
        SignAcctInfo signAcctInfo = (SignAcctInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.SIGN_ACCT_INFO);
        upPayerBean.setAccNo(xmlTreeUtil.getXmlTreeStringValue("payerInf/acctNo"));
        upPayerBean.setName(xmlTreeUtil.getXmlTreeStringValue("payerInfo/acctName"));

        genC2BNoRequest.setPayerInfo(upPayerBean);

        String payType = PayTypeEnum.BANK_CARD.getPayType();
        // 根据渠道&卡号获取用户号
        // 01 它行，卡号需要转换成协议号
        if ("01".equals(xmlTreeUtil.getXmlTreeStringValue("cardType"))) {
            // 通道签约时，填签约银行联行行号 + "|" + 通道返回的协议号
            String signToken = Objects.requireNonNull(signAcctInfo).getSignToken().split("\\|")[1];
            genC2BNoRequest.getPayerInfo().setAccNo(signToken);
            payType = PayTypeEnum.OTHER_BANK_CARD.getPayType();
        }

        // TODO ChanlId手机和直销、慧济生活等如何区分【应为商户ID】
        AddnCondition addnCondition = null;
        //附加条件处理信息	addnCondition
        genC2BNoRequest.setAddnCondition(addnCondition);

        //风控信息	riskInfo
//        RiskInfoBean riskInfoBean = new RiskInfoBean();
//        BeanUtil.beanCopy(bankGenC2BNoRequest.getRiskInfo(), riskInfoBean);
//        genC2BNoRequest.setRiskInfoBean(riskInfoBean);
//
//        //银联机构号	issInsCode
//        genC2BNoRequest.setIssInsCode(strUnonPayCode);
//        //订单号	orderId
//        genC2BNoRequest.setOrderId(userOrderInfo.getSysSeqNum());
//        //订单发送时间	orderTime
//        genC2BNoRequest.setOrderTime(userOrderInfo.getOrderCreateTime());
//        //二维码有效时间
//        genC2BNoRequest.setQrValidTime(bankGenC2BNoRequest.getQrValidTime());
//
//        JSONObject reqRJson = new JSONObject();
//        reqRJson.put("instId", bankGenC2BNoRequest.getHeader().getInstId());
//        reqRJson.put("flowNo", userOrderInfo.getSysSeqNum());
//        //请求方保留域	reqReserved
//        genC2BNoRequest.setReqReserved(Base64.encodeBase64String(reqRJson.toJSONString().getBytes()));
//        // 01-借记
//        //  02-贷记
//        if("01".equals(bankGenC2BNoRequest.getPayerInfo().getCardAttr())) {
//            // 35-借记卡
//            genC2BNoRequest.setQrType("35");
//        }
//        else if("02".equals(bankGenC2BNoRequest.getPayerInfo().getCardAttr())) {
//            genC2BNoRequest.setQrType("51");//51-贷记卡
//        }
//        else {
//            genC2BNoRequest.setQrType("40");//40－其他
//        }

        //TODO 待赋值
        rglog.debug("UPQC C2B码申请请求:<{}>", JSON.toJSONString(genC2BNoRequest));

        return genC2BNoRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        //此交易不登记支付订单
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        GenC2BNoRequest genC2BNoRequest = (GenC2BNoRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<GenC2BNoResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPQC_PAYER_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.UPQC_GEN_C2B_NO_METHOD, genC2BNoRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.UPQC_PAYER_SERVICE, ShareServiceConstant.UPQC_GEN_C2B_NO_METHOD, genC2BNoRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPQC_PAYER_SERVICE_INNER_PATH);
                callResult = (Result<GenC2BNoResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.UPQC_GEN_C2B_NO_METHOD, genC2BNoRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<GenC2BNoResponse>) dubboService.callDubboService(ShareServiceConstant.UPQC_PAYER_SERVICE, ShareServiceConstant.UPQC_GEN_C2B_NO_METHOD, genC2BNoRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        //此交易不登记订单
        return null;
    }
}
